import React, { useEffect, useRef, useState, useCallback } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import Bird from '../components/Bird';
import Fish from '../components/Fish';
import Boat from '../components/Boat';
import { predictImage } from '../utils/onnxInference';
import type { PredictionResult } from '../utils/onnxInference';
import { saveDrawing as saveDrawingToBackend } from '../utils/drawingApi';
import { useAuth } from '../contexts/AuthContext';
import type { CreateDrawingRequest, DrawingType } from '../types/drawing';

const DrawingPage: React.FC = () => {
  const { user, isAuthenticated } = useAuth();
  const navigate = useNavigate();
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const [isDrawing, setIsDrawing] = useState(false);
  const [ctx, setCtx] = useState<CanvasRenderingContext2D | null>(null);
  const [brushColor, setBrushColor] = useState('#000000');
  // 移除背景色，使用透明背景
  // 移除未使用的背景色状态
  const [brushSize, setBrushSize] = useState(5);
  const [brushOpacity, setBrushOpacity] = useState(1);

  const [saveStatus, setSaveStatus] = useState('');
  const [history, setHistory] = useState<string[]>([]);
  const [historyIndex, setHistoryIndex] = useState(-1);
  
  // 防抖函数
  const debounce = useCallback((func: Function, delay: number) => {
    let timeoutId: number;
    return (...args: any[]) => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => func.apply(null, args), delay) as unknown as number;
    };
  }, []);
  const [tool, setTool] = useState<'brush' | 'eraser'>('brush');
  const [brushType, setBrushType] = useState<'round' | 'square' | 'sharp' | 'spray'>('round');
  const [selectedType, setSelectedType] = useState<'bird' | 'fish' | 'boat' | null>(null);
  const [showTypeSelection, setShowTypeSelection] = useState(false);
  const [aiPrediction, setAiPrediction] = useState<PredictionResult | null>(null);
  const [isPredicting, setIsPredicting] = useState(false);
  const [predictionAccuracy, setPredictionAccuracy] = useState<number>(0);
  const [predictionError, setPredictionError] = useState<string>('');
  const [predictionStatus, setPredictionStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [isSaving, setIsSaving] = useState(false);
  const [drawingTitle, setDrawingTitle] = useState('');
  // 移除：页面级移动端纵向提示（改为全局在 App.tsx 实现）
  // const [isPortraitMobile, setIsPortraitMobile] = useState(false);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    const context = canvas.getContext('2d', { alpha: true });
    if (!context) return;
    setCtx(context);

    // 设置透明背景
    context.clearRect(0, 0, canvas.width, canvas.height);

    const handleResize = () => {
      if (!canvas) return;
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
      // 保持透明背景
      context.clearRect(0, 0, canvas.width, canvas.height);
    };
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // 移除：页面级监听方向变化（改为全局在 App.tsx 实现）
  // useEffect(() => {
  //   const update = () => {
  //     const isMobile = window.innerWidth < 1024; // 粗略判断移动/平板
  //     const isPortrait = window.innerHeight > window.innerWidth;
  //     setIsPortraitMobile(isMobile && isPortrait);
  //   };
  //   update();
  //   window.addEventListener('resize', update);
  //   window.addEventListener('orientationchange', update as any);
  //   return () => {
  //     window.removeEventListener('resize', update);
  //     window.removeEventListener('orientationchange', update as any);
  //   };
  // }, []);

  // 保留：尝试在移动端默认锁定为横屏（若浏览器允许）
  useEffect(() => {
    const isMobile = window.innerWidth < 1024;
    if (!isMobile) return;
    const tryLockLandscape = async () => {
      try {
        const anyScreen: any = screen as any;
        if (anyScreen.orientation?.lock) {
          await anyScreen.orientation.lock('landscape');
        }
      } catch {
        // 失败则交由全局遮罩引导
      }
    };
    tryLockLandscape();
  }, []);

  useEffect(() => {
    if (!ctx) return;
    ctx.lineCap = brushType === 'round' ? 'round' : 'butt';
    ctx.lineJoin = brushType === 'round' ? 'round' : brushType === 'square' ? 'miter' : 'bevel';

    // 统一设置宽度与透明度
    ctx.lineWidth = brushSize;
    ctx.globalAlpha = brushOpacity;

    if (tool === 'eraser') {
      // 关键修复：destination-out 需要源 alpha > 0，不能使用透明颜色
      ctx.globalCompositeOperation = 'destination-out';
      ctx.strokeStyle = 'rgba(0,0,0,1)';
      ctx.fillStyle = 'rgba(0,0,0,1)';
    } else {
      ctx.globalCompositeOperation = 'source-over';
      const drawColor = brushType === 'spray' ? `${brushColor}33` : brushColor;
      ctx.strokeStyle = drawColor;
      ctx.fillStyle = drawColor;
    }
  }, [ctx, tool, brushColor, brushSize, brushType, brushOpacity]);

  useEffect(() => {
    if (!ctx || !canvasRef.current) return;
    // 清除画布而不是填充背景色
    ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
  }, [ctx]);

  const getOffsets = (e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>) => {
    const canvas = canvasRef.current;
    if (!canvas) return { x: 0, y: 0 };
    
    let clientX, clientY;
    
    if ('touches' in e) {
      // 触摸事件
      const touch = e.touches[0];
      clientX = touch.clientX;
      clientY = touch.clientY;
    } else {
      // 鼠标事件
      clientX = e.clientX;
      clientY = e.clientY;
    }
    
    const rect = canvas.getBoundingClientRect();
    const x = clientX - rect.left;
    const y = clientY - rect.top;
    
    return { x, y };
  };

  const startDrawing = (e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>) => {
    if (!ctx) return;
    const { x, y } = getOffsets(e);
    ctx.beginPath();
    ctx.moveTo(x, y);
    setIsDrawing(true);
  };

  const draw = (e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>) => {
    if (!isDrawing || !ctx) return;
    const { x, y } = getOffsets(e);
    
    if (brushType === 'spray') {
      // 喷雾效果：在随机位置绘制多个点
      const points = 20;
      const radius = brushSize * 2;
      
      for (let i = 0; i < points; i++) {
        const angle = Math.random() * Math.PI * 2;
        const distance = Math.random() * radius;
        const sprayX = x + Math.cos(angle) * distance;
        const sprayY = y + Math.sin(angle) * distance;
        
        ctx.beginPath();
        ctx.arc(sprayX, sprayY, brushSize / 4, 0, Math.PI * 2);
        ctx.fill();
      }
    } else {
      // 普通画笔
      ctx.lineTo(x, y);
      ctx.stroke();
    }
  };

  const stopDrawing = () => {
    if (!ctx || !canvasRef.current) return;
    ctx.closePath();
    setIsDrawing(false);
    
    // 保存到历史记录
    saveToHistory();
  };

  const saveToHistory = useCallback(debounce(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    
    const dataUrl = canvas.toDataURL('image/png');
    const newHistory = history.slice(0, historyIndex + 1);
    
    // 限制历史记录长度，防止内存占用过大
    if (newHistory.length > 50) {
      newHistory.shift();
    }
    
    newHistory.push(dataUrl);
    
    setHistory(newHistory);
    setHistoryIndex(newHistory.length - 1);
  }, 300), [history, historyIndex]);

  const undo = () => {
    if (historyIndex > 0) {
      const newIndex = historyIndex - 1;
      setHistoryIndex(newIndex);
      restoreFromHistory(newIndex);
    }
  };

  const redo = () => {
    if (historyIndex < history.length - 1) {
      const newIndex = historyIndex + 1;
      setHistoryIndex(newIndex);
      restoreFromHistory(newIndex);
    }
  };

  const restoreFromHistory = (index: number) => {
    if (!ctx || !canvasRef.current || index < 0 || index >= history.length) return;
    
    const img = new Image();
    img.onload = () => {
      ctx.clearRect(0, 0, canvasRef.current!.width, canvasRef.current!.height);
      ctx.drawImage(img, 0, 0);
    };
    img.src = history[index];
  };

  const clearCanvas = () => {
    if (!ctx || !canvasRef.current) return;
    ctx.globalCompositeOperation = 'source-over';
    // 使用clearRect清除画布，保持透明
    ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
  };

  const exportDrawing = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const dataUrl = canvas.toDataURL('image/png');
    const link = document.createElement('a');
    link.download = `seasky-drawing-${new Date().toISOString().slice(0, 10)}.png`;
    link.href = dataUrl;
    link.click();
  };

  const predictDrawing = async () => {
    const canvas = canvasRef.current;
    if (!canvas) {
      setPredictionError('画布未找到');
      setPredictionStatus('error');
      return;
    }
    
    // 检查画布是否有内容
    const ctx = canvas.getContext('2d');
    if (!ctx) {
      setPredictionError('无法获取画布上下文');
      setPredictionStatus('error');
      return;
    }
    
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const hasContent = imageData.data.some((value, index) => {
      // 检查alpha通道，如果不是完全透明就认为有内容
      return index % 4 === 3 && value > 0;
    });
    
    if (!hasContent) {
      setPredictionError('请先在画布上绘制一些内容');
      setPredictionStatus('error');
      setTimeout(() => {
        setPredictionError('');
        setPredictionStatus('idle');
      }, 3000);
      return;
    }
    
    setIsPredicting(true);
    setPredictionStatus('loading');
    setPredictionError('');
    setAiPrediction(null);
    setPredictionAccuracy(0);
    
    try {
      console.log('开始AI识别...');
      const dataUrl = canvas.toDataURL('image/png');
      
      if (!dataUrl || dataUrl === 'data:,') {
        throw new Error('无法获取画布图像数据');
      }
      
      const result = await predictImage(dataUrl);
      
      if (!result || typeof result.confidence !== 'number') {
        throw new Error('AI识别返回无效结果');
      }
      
      setAiPrediction(result);
      
      // 计算准确度百分比
      const accuracy = Math.round(result.confidence * 100);
      setPredictionAccuracy(accuracy);
      setPredictionStatus('success');
      
      console.log(`AI识别完成: ${result.label} (${accuracy}%)`);
      
      // 如果准确度超过60%，自动选择类型
      if (accuracy >= 60) {
        const typeMap: { [key: string]: 'bird' | 'fish' | 'boat' } = {
          'bird': 'bird',
          'fish': 'fish', 
          'boat': 'boat'
        };
        if (result.label in typeMap) {
          setSelectedType(typeMap[result.label as keyof typeof typeMap]);
          setSaveStatus(`AI识别成功！检测到${result.emoji} ${result.label}，准确度${accuracy}%`);
        }
      } else {
        setSaveStatus(`AI识别完成，但准确度较低(${accuracy}%)，建议重新绘制`);
      }
      
      // 清除状态消息
      setTimeout(() => {
        setSaveStatus('');
      }, 5000);
      
    } catch (error) {
      console.error('AI预测失败:', error);
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      setPredictionError(`AI识别失败: ${errorMessage}`);
      setPredictionStatus('error');
      setSaveStatus('AI识别失败，请检查网络连接或重试');
      
      // 清除错误状态
      setTimeout(() => {
        setPredictionError('');
        setPredictionStatus('idle');
        setSaveStatus('');
      }, 5000);
    } finally {
      setIsPredicting(false);
    }
  };

  const saveDrawing = async () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    
    // 防止重复保存
    if (isSaving) {
      return;
    }
    
    // 检查用户是否已登录
    if (!isAuthenticated || !user) {
      setSaveStatus('请先登录后再保存画作');
      setTimeout(() => setSaveStatus(''), 3000);
      return;
    }
    
    // 检查是否已经进行AI预测
    if (!aiPrediction) {
      setSaveStatus('请先进行AI预测');
      setTimeout(() => setSaveStatus(''), 2000);
      return;
    }
    
    // 检查准确度是否达到60%
    if (predictionAccuracy < 60) {
      setSaveStatus(`准确度不足60%（当前${predictionAccuracy}%），无法保存`);
      setTimeout(() => setSaveStatus(''), 2000);
      return;
    }
    
    // 如果准确度超过60%，自动选择类型并保存
    if (predictionAccuracy >= 60 && aiPrediction) {
      const typeMap: { [key: string]: DrawingType } = {
        'bird': 'bird',
        'fish': 'fish', 
        'boat': 'boat'
      };
      
      if (aiPrediction.label in typeMap) {
        const autoType = typeMap[aiPrediction.label as keyof typeof typeMap];
        setSelectedType(autoType);
        setIsSaving(true);
        
        try {
          const dataUrl = canvas.toDataURL('image/png');
          
          // 生成默认标题
          const defaultTitle = drawingTitle || `${aiPrediction.emoji} ${aiPrediction.label} - ${new Date().toLocaleDateString()}`;
          
          // 准备后端保存数据
          const drawingData: CreateDrawingRequest = {
            title: defaultTitle,
            imageData: dataUrl,
            drawingType: autoType,
            aiPrediction: aiPrediction.label,
            aiAccuracy: predictionAccuracy,
            canvasWidth: canvas.width,
            canvasHeight: canvas.height,
            brushSettings: {
              size: brushSize,
              color: brushColor,
              opacity: brushOpacity,
              tool: tool === 'eraser' ? 'eraser' : brushType === 'spray' ? 'spray' : 'brush'
            },
            isPublic: false, // 默认私有
            tags: aiPrediction.label
          };
          
          // 保存到后端
          const savedDrawing = await saveDrawingToBackend(drawingData, user.id);
          
          // 同时保存到本地存储作为备份
          const drawings = JSON.parse(localStorage.getItem('seaSkyDrawings') || '[]');
          const newDrawing = { 
            id: savedDrawing.id, 
            dataUrl, 
            timestamp: new Date().toLocaleString(),
            type: autoType,
            randomDelay: Math.floor(Math.random() * 5),
            aiPrediction: aiPrediction.label,
            accuracy: predictionAccuracy,
            title: defaultTitle,
            backendId: savedDrawing.id
          };
          drawings.push(newDrawing);
          localStorage.setItem('seaSkyDrawings', JSON.stringify(drawings));
          
          setSaveStatus('AI自动识别并保存成功！');
          
          // 关闭所有弹窗
          setShowTypeSelection(false);
          
          setTimeout(() => {
            setSaveStatus('');
            setAiPrediction(null);
            setPredictionAccuracy(0);
            setDrawingTitle('');
            // 跳转到首页
            navigate('/');
          }, 1500);
        } catch (error) {
          console.error('保存画作失败:', error);
          
          // 如果后端保存失败，仍然保存到本地
          try {
            const dataUrl = canvas.toDataURL('image/png');
            const drawings = JSON.parse(localStorage.getItem('seaSkyDrawings') || '[]');
            const newDrawing = { 
              id: Date.now(), 
              dataUrl, 
              timestamp: new Date().toLocaleString(),
              type: autoType,
              randomDelay: Math.floor(Math.random() * 5),
              aiPrediction: aiPrediction.label,
              accuracy: predictionAccuracy,
              title: drawingTitle || `${aiPrediction.emoji} ${aiPrediction.label} - ${new Date().toLocaleDateString()}`,
              backendSyncFailed: true
            };
            drawings.push(newDrawing);
            localStorage.setItem('seaSkyDrawings', JSON.stringify(drawings));
            setSaveStatus('后端保存失败，已保存到本地');
          } catch (localError) {
            setSaveStatus('保存失败，请重试');
          }
          
          setTimeout(() => setSaveStatus(''), 3000);
        } finally {
          setIsSaving(false);
        }
      } else {
        setSaveStatus('AI识别类型不支持，无法保存');
        setTimeout(() => setSaveStatus(''), 2000);
      }
    }
  };

  return (
    <div className="drawing-page">
      <canvas
        ref={canvasRef}
        onMouseDown={startDrawing}
        onMouseMove={draw}
        onMouseUp={stopDrawing}
        onMouseLeave={stopDrawing}
        onTouchStart={startDrawing}
        onTouchMove={draw}
        onTouchEnd={stopDrawing}
        className="drawing-canvas"
      />

      {saveStatus && (
        <div className="toast toast-top toast-center">
          <div className="alert alert-info">
            <span>{saveStatus}</span>
          </div>
        </div>
      )}
      {/* AI预测状态和结果显示 */}
      {(predictionStatus !== 'idle' || aiPrediction || predictionError) && (
        <div className="modal modal-open">
          <div className="modal-box">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-bold text-lg">AI识别</h3>
              {predictionStatus === 'loading' && (
                <div className="flex items-center gap-2">
                  <span className="loading loading-spinner loading-sm"></span>
                  <span>识别中...</span>
                </div>
              )}
            </div>
            
            {predictionError && (
              <div className="alert alert-error mb-4">
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <span>{predictionError}</span>
              </div>
            )}
            
            {aiPrediction && predictionStatus === 'success' && (
              <div className="space-y-4">
                <div className="flex items-center gap-4 p-4 bg-base-200 rounded-lg">
                  <span className="text-4xl">{aiPrediction.emoji}</span>
                  <div className="flex-1">
                    <div className="font-semibold text-lg">{aiPrediction.label}</div>
                    <div className="text-sm opacity-70">准确度: {predictionAccuracy}%</div>
                  </div>
                </div>
                <div className="alert">
                  {predictionAccuracy >= 60 ? (
                    <div className="alert alert-success">
                      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                      <span>准确度达标，可以保存</span>
                    </div>
                  ) : (
                    <div className="alert alert-warning">
                      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                      </svg>
                      <span>准确度不足60%，建议重新绘制</span>
                    </div>
                  )}
                </div>
                <div className="modal-action">
                  <button 
                    onClick={() => {
                      setAiPrediction(null);
                      setPredictionStatus('idle');
                      setPredictionAccuracy(0);
                    }}
                    className="btn btn-ghost"
                  >
                    关闭
                  </button>
                  {predictionAccuracy >= 60 && (
                    <button 
                      onClick={saveDrawing}
                      className="btn btn-primary"
                    >
                      快速保存
                    </button>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>
      )}
      
      {showTypeSelection && (
        <div className="modal modal-open">
          <div className="modal-box">
            <h3 className="font-bold text-lg mb-4">选择一个类型</h3>
            <div className="grid grid-cols-3 gap-4 mb-6">
              <div 
                className={`card bg-base-200 cursor-pointer transition-all hover:bg-base-300 ${selectedType === 'bird' ? 'ring-2 ring-primary' : ''}`} 
                onClick={() => setSelectedType('bird')}
              >
                <div className="card-body items-center text-center p-4">
                  <svg width="60" height="60" viewBox="0 0 100 100">
                    <Bird x={50} y={50} size={50} />
                  </svg>
                  <span className="font-medium">鸟</span>
                </div>
              </div>
              <div 
                className={`card bg-base-200 cursor-pointer transition-all hover:bg-base-300 ${selectedType === 'fish' ? 'ring-2 ring-primary' : ''}`} 
                onClick={() => setSelectedType('fish')}
              >
                <div className="card-body items-center text-center p-4">
                  <svg width="60" height="60" viewBox="0 0 100 100">
                    <Fish x={50} y={50} size={50} />
                  </svg>
                  <span className="font-medium">鱼</span>
                </div>
              </div>
              <div 
                className={`card bg-base-200 cursor-pointer transition-all hover:bg-base-300 ${selectedType === 'boat' ? 'ring-2 ring-primary' : ''}`} 
                onClick={() => setSelectedType('boat')}
              >
                <div className="card-body items-center text-center p-4">
                  <svg width="60" height="60" viewBox="0 0 100 100">
                    <Boat x={50} y={50} size={50} />
                  </svg>
                  <span className="font-medium">船</span>
                </div>
              </div>
            </div>
            <div className="modal-action">
              <button 
                onClick={() => {
                  setShowTypeSelection(false);
                  setSaveStatus('');
                }}
                className="btn btn-ghost"
              >
                取消
              </button>
              <button 
                onClick={saveDrawing} 
                disabled={!selectedType}
                className={`btn btn-primary ${!selectedType ? 'btn-disabled' : ''}`}
              >
                确认保存
              </button>
            </div>
          </div>
        </div>
      )}

      <div className="fixed top-4 left-4 right-4 z-10">
        <div className="card bg-base-100 shadow-lg">
          <div className="card-body p-4">
            <div className="flex flex-wrap gap-4 items-center">
              {/* 工具选择 */}
              <div className="flex gap-2">
                <button 
                  className={`btn btn-sm ${tool === 'brush' ? 'btn-primary' : 'btn-outline'}`} 
                  onClick={() => setTool('brush')}
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
                  </svg>
                  画笔
                </button>
                <button 
                  className={`btn btn-sm ${tool === 'eraser' ? 'btn-primary' : 'btn-outline'}`} 
                  onClick={() => setTool('eraser')}
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                  橡皮擦
                </button>
              </div>

              {/* 画笔样式 */}
              <div className="flex gap-1">
                <span className="text-sm font-medium mr-2">样式:</span>
                <button className={`btn btn-xs ${brushType === 'round' ? 'btn-primary' : 'btn-outline'}`} onClick={() => setBrushType('round')}>圆形</button>
                <button className={`btn btn-xs ${brushType === 'square' ? 'btn-primary' : 'btn-outline'}`} onClick={() => setBrushType('square')}>方形</button>
                <button className={`btn btn-xs ${brushType === 'sharp' ? 'btn-primary' : 'btn-outline'}`} onClick={() => setBrushType('sharp')}>尖角</button>
                <button className={`btn btn-xs ${brushType === 'spray' ? 'btn-primary' : 'btn-outline'}`} onClick={() => setBrushType('spray')}>喷雾</button>
              </div>

              {/* 颜色选择 */}
              <div className="flex items-center gap-2">
                <input 
                  type="color" 
                  value={brushColor} 
                  onChange={(e) => setBrushColor(e.target.value)} 
                  className="w-8 h-8 rounded border-2 border-base-300 cursor-pointer" 
                />
                <div className="flex gap-1">
                  {['#000000', '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF', '#FFFFFF'].map((color) => (
                    <div 
                      key={color} 
                      className={`w-6 h-6 rounded cursor-pointer border-2 hover:scale-110 transition-transform ${
                        color === '#FFFFFF' ? 'border-base-300' : 'border-transparent'
                      }`}
                      style={{ backgroundColor: color === '#FFFFFF' ? '#f0f0f0' : color }} 
                      onClick={() => setBrushColor(color)} 
                      title={color} 
                    />
                  ))}
                </div>
              </div>

              {/* 大小控制 */}
              <div className="flex items-center gap-2">
                <span className="text-sm font-medium">大小:</span>
                <input 
                  type="range" 
                  min={1} 
                  max={50} 
                  value={brushSize} 
                  onChange={(e) => setBrushSize(Number(e.target.value))} 
                  className="range range-primary range-sm w-20" 
                />
                <span className="text-sm min-w-[40px]">{brushSize}px</span>
              </div>
              
              {/* 透明度控制 */}
              <div className="flex items-center gap-2">
                <span className="text-sm font-medium">透明度:</span>
                <input 
                  type="range" 
                  min={0.1} 
                  max={1} 
                  step={0.1}
                  value={brushOpacity} 
                  onChange={(e) => setBrushOpacity(Number(e.target.value))} 
                  className="range range-primary range-sm w-20" 
                />
                <span className="text-sm min-w-[40px]">{Math.round(brushOpacity * 100)}%</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 操作按钮 */}
      <div className="fixed bottom-4 left-4 right-4 z-10">
        <div className="card bg-base-100 shadow-lg">
          <div className="card-body p-4">
            <div className="flex flex-wrap gap-2 justify-center">
              <button 
                onClick={undo} 
                disabled={historyIndex <= 0} 
                className={`btn btn-sm ${historyIndex <= 0 ? 'btn-disabled' : 'btn-outline'}`}
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" />
                </svg>
                撤销
              </button>
              <button 
                onClick={redo} 
                disabled={historyIndex >= history.length - 1} 
                className={`btn btn-sm ${historyIndex >= history.length - 1 ? 'btn-disabled' : 'btn-outline'}`}
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 10H11a8 8 0 00-8 8v2m18-10l-6 6m6-6l-6-6" />
                </svg>
                重做
              </button>
              <button onClick={clearCanvas} className="btn btn-sm btn-warning">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
                清除画布
              </button>
              <button 
                onClick={predictDrawing} 
                className={`btn btn-sm ${
                  predictionStatus === 'loading' ? 'btn-disabled loading' : 
                  predictionStatus === 'success' ? 'btn-success' : 
                  predictionStatus === 'error' ? 'btn-error' : 
                  'btn-info'
                }`}
                disabled={isPredicting || predictionStatus === 'loading'}
              >
                {predictionStatus === 'loading' ? (
                  <span className="loading loading-spinner loading-xs"></span>
                ) : (
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                  </svg>
                )}
                {predictionStatus === 'loading' && 'AI识别中...'}
                {predictionStatus === 'success' && '识别完成'}
                {predictionStatus === 'error' && '识别失败'}
                {predictionStatus === 'idle' && 'AI识别'}
              </button>
              <button onClick={saveDrawing} className="btn btn-sm btn-primary">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
                </svg>
                保存画作
              </button>
              <button onClick={exportDrawing} className="btn btn-sm btn-secondary">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
                导出画作
              </button>
              <Link to="/" className="btn btn-sm btn-ghost">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
                </svg>
                返回首页
              </Link>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default DrawingPage;

